<!doctype html>
<script src="/resources/testdriver.js"></script>
<script src="/resources/testdriver-vendor.js"></script>
<script type="module">
import {request_options_with_mediation_required} from './fedcm-helper.sub.js';

// Loading fedcm-iframe.html in the test will make a FedCM call on load, and
// trigger a postMessage upon completion.
//
// message {
//   string result: "Pass" | "Fail"
//   string token: token.token
//   string errorType: error.name
// }

window.onload = async () => {
  window.test_driver.set_test_context(window.top);
  // Use this variable to stop trying to select an account once the get() promise is resolved.
  let cancelHelper = false;
  try {
    const credentialPromise = navigator.credentials.get(request_options_with_mediation_required());
    async function helper() {
      try {
        if (cancelHelper)
          return;

        await window.test_driver.select_fedcm_account(0);
      } catch (ex) {
        setTimeout(helper, 100);
      }
    }
    helper();
    const cred = await credentialPromise;
    window.top.postMessage({result: "Pass", token: cred.token}, '*');
  } catch (error) {
    window.top.postMessage({result: "Fail", errorType: error.name}, '*');
  }
  // In case the get() call fails and no accounts may be selected, force the
  // helper function to stop calling itself.
  cancelHelper = true;
};

</script>
